<template>
  <view class="my-goods-page">
    <!-- 导航栏 -->
    <uni-nav-bar
      title="我的发布"
      :border="false"
      background-color="#07C160"
      color="#FFFFFF"
      @clickLeft="goBack"
    />

    <!-- 状态筛选 -->
    <view class="filter-tabs">
      <view
        v-for="(tab, index) in statusTabs"
        :key="index"
        class="tab-item"
        :class="{ active: currentTab === index }"
        @click="switchTab(index)"
      >
        <text class="tab-text">{{ tab.name }}</text>
        <text class="tab-count" v-if="tab.count > 0">({{ tab.count }})</text>
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="goods-list">
      <view
        v-for="item in goodsList"
        :key="item.id"
        class="goods-item"
        @click="goToDetail(item.id)"
      >
        <image class="goods-image" :src="item.images[0]" mode="aspectFill" />
        <view class="goods-info">
          <view class="goods-title">{{ item.title }}</view>
          <view class="goods-price">¥{{ item.price }}</view>
          <view class="goods-meta">
            <text class="publish-time">{{ formatTime(item.createdAt) }}</text>
            <text class="view-count">{{ item.viewCount }}次浏览</text>
          </view>
          <view class="goods-status">
            <uni-tag
              :text="getStatusText(item.status)"
              :type="getStatusType(item.status)"
              size="small"
            />
          </view>
        </view>
        <view class="goods-actions">
          <button
            class="action-btn edit-btn"
            @click.stop="editGoods(item)"
            v-if="item.status === 'active'"
          >
            编辑
          </button>
          <button class="action-btn delete-btn" @click.stop="deleteGoods(item)">
            删除
          </button>
          <button
            class="action-btn republish-btn"
            @click.stop="republishGoods(item)"
            v-if="item.status === 'sold'"
          >
            重新发布
          </button>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="goodsList.length === 0 && !loading">
      <image
        class="empty-image"
        src="/static/images/empty-goods.png"
        mode="aspectFit"
      />
      <text class="empty-text">暂无发布的商品</text>
      <button class="publish-btn" @click="goToPublish">去发布</button>
    </view>

    <!-- 加载状态 -->
    <uni-load-more
      :status="loadMoreStatus"
      :content-text="loadMoreText"
      v-if="goodsList.length > 0"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { getUserGoods, deleteUserGoods } from "../../api/goods";
import { formatTime } from "../../utils/format";
import { GoodsItem, GoodsStatus } from "../../types/goods";

// 状态筛选标签
const statusTabs = ref([
  { name: "全部", status: "", count: 0 },
  { name: "在售", status: "active", count: 0 },
  { name: "已售", status: "sold", count: 0 },
  { name: "下架", status: "inactive", count: 0 },
]);

// 当前选中的标签
const currentTab = ref(0);

// 商品列表
const goodsList = ref<GoodsItem[]>([]);

// 加载状态
const loading = ref(false);
const loadMoreStatus = ref("more");
const loadMoreText = reactive({
  contentdown: "上拉加载更多",
  contentrefresh: "加载中...",
  contentnomore: "没有更多了",
});

// 分页参数
const pageParams = reactive({
  page: 1,
  pageSize: 10,
  status: "",
});

// 页面加载时获取数据
onMounted(() => {
  loadGoodsList();
});

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 切换标签
const switchTab = (index: number) => {
  currentTab.value = index;
  pageParams.status = statusTabs.value[index].status;
  pageParams.page = 1;
  goodsList.value = [];
  loadGoodsList();
};

// 加载商品列表
const loadGoodsList = async (loadMore = false) => {
  if (loading.value) return;

  loading.value = true;
  loadMoreStatus.value = "loading";

  try {
    // TODO: 调用API获取用户商品列表
    // const response = await getUserGoods(pageParams)
    // const newGoods = response.data.list

    // 模拟数据
    const mockGoods: GoodsItem[] = [
      {
        id: "1",
        title: "九成新iPhone 14 Pro",
        description: "个人自用，成色很好",
        price: 6999,
        originalPrice: 7999,
        images: ["/static/images/goods1.jpg"],
        category: { id: "3", name: "数码", icon: "phone" },
        status: "active" as GoodsStatus,
        viewCount: 128,
        favoriteCount: 15,
        createdAt: "2024-01-15T10:30:00Z",
        updatedAt: "2024-01-15T10:30:00Z",
        user: {
          id: "123",
          nickname: "张先生",
          avatar: "/static/images/avatar1.jpg",
          location: "北京市朝阳区",
        },
      },
      {
        id: "2",
        title: "全新AirPods Pro",
        description: "未拆封，原价购买",
        price: 1599,
        originalPrice: 1999,
        images: ["/static/images/goods2.jpg"],
        category: { id: "3", name: "数码", icon: "headphones" },
        status: "sold" as GoodsStatus,
        viewCount: 89,
        favoriteCount: 8,
        createdAt: "2024-01-10T14:20:00Z",
        updatedAt: "2024-01-10T14:20:00Z",
        user: {
          id: "123",
          nickname: "张先生",
          avatar: "/static/images/avatar1.jpg",
          location: "北京市朝阳区",
        },
      },
    ];

    // 筛选数据
    const filteredGoods = pageParams.status
      ? mockGoods.filter((item) => item.status === pageParams.status)
      : mockGoods;

    if (loadMore) {
      goodsList.value.push(...filteredGoods);
    } else {
      goodsList.value = filteredGoods;
    }

    // 更新标签计数
    updateTabCounts(mockGoods);

    // 更新加载状态
    if (filteredGoods.length < pageParams.pageSize) {
      loadMoreStatus.value = "noMore";
    } else {
      loadMoreStatus.value = "more";
      pageParams.page++;
    }
  } catch (error) {
    console.error("加载商品列表失败:", error);
    uni.showToast({
      title: "加载失败",
      icon: "none",
    });
    loadMoreStatus.value = "more";
  } finally {
    loading.value = false;
  }
};

// 更新标签计数
const updateTabCounts = (allGoods: GoodsItem[]) => {
  statusTabs.value[0].count = allGoods.length;
  statusTabs.value[1].count = allGoods.filter(
    (item) => item.status === "available"
  ).length;
  statusTabs.value[2].count = allGoods.filter(
    (item) => item.status === "sold"
  ).length;
  statusTabs.value[3].count = allGoods.filter(
    (item) => item.status === "offline"
  ).length;
};

// 获取状态文本
const getStatusText = (status: GoodsStatus) => {
  const statusMap = {
    available: "在售",
    sold: "已售",
    reserved: "预定",
    offline: "下架",
  };
  return statusMap[status] || "未知";
};

// 获取状态类型
const getStatusType = (status: GoodsStatus) => {
  const typeMap = {
    available: "success",
    sold: "warning",
    reserved: "primary",
    offline: "info",
  };
  return typeMap[status] || "default";
};

// 跳转到商品详情
const goToDetail = (goodsId: string) => {
  uni.navigateTo({
    url: `/pages/goods/detail?id=${goodsId}`,
  });
};

// 编辑商品
const editGoods = (goods: GoodsItem) => {
  uni.navigateTo({
    url: `/pages/goods/edit?id=${goods.id}`,
  });
};

// 删除商品
const deleteGoods = (goods: GoodsItem) => {
  uni.showModal({
    title: "确认删除",
    content: `确定要删除商品"${goods.title}"吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          // TODO: 调用删除API
          // await deleteUserGoods(goods.id)

          // 从列表中移除
          const index = goodsList.value.findIndex(
            (item) => item.id === goods.id
          );
          if (index > -1) {
            goodsList.value.splice(index, 1);
          }

          uni.showToast({
            title: "删除成功",
            icon: "success",
          });
        } catch (error) {
          console.error("删除商品失败:", error);
          uni.showToast({
            title: "删除失败",
            icon: "none",
          });
        }
      }
    },
  });
};

// 重新发布商品
const republishGoods = (goods: GoodsItem) => {
  uni.showModal({
    title: "重新发布",
    content: `确定要重新发布商品"${goods.title}"吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          // TODO: 调用重新发布API

          // 更新商品状态
          goods.status = GoodsStatus.AVAILABLE;

          uni.showToast({
            title: "重新发布成功",
            icon: "success",
          });

          // 刷新列表
          loadGoodsList();
        } catch (error) {
          console.error("重新发布失败:", error);
          uni.showToast({
            title: "重新发布失败",
            icon: "none",
          });
        }
      }
    },
  });
};

// 跳转到发布页面
const goToPublish = () => {
  uni.switchTab({
    url: "/pages/goods/publish",
  });
};
</script>

<style lang="scss" scoped>
.my-goods-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.filter-tabs {
  background-color: #ffffff;
  display: flex;
  padding: 0 30rpx;
  border-bottom: 1rpx solid #eeeeee;
}

.tab-item {
  flex: 1;
  padding: 30rpx 0;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  cursor: pointer;

  &.active {
    .tab-text {
      color: #07c160;
      font-weight: bold;
    }

    &::after {
      content: "";
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 60rpx;
      height: 4rpx;
      background-color: #07c160;
      border-radius: 2rpx;
    }
  }
}

.tab-text {
  font-size: 28rpx;
  color: #666666;
  transition: color 0.3s;
}

.tab-count {
  font-size: 24rpx;
  color: #999999;
  margin-left: 5rpx;
}

.goods-list {
  padding: 20rpx 30rpx;
}

.goods-item {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.goods-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
}

.goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-title {
  font-size: 30rpx;
  color: #333333;
  font-weight: 500;
  margin-bottom: 10rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-price {
  font-size: 32rpx;
  color: #ff4444;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.goods-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15rpx;
}

.publish-time,
.view-count {
  font-size: 24rpx;
  color: #999999;
}

.goods-status {
  display: flex;
  align-items: center;
}

.goods-actions {
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 15rpx;
  margin-left: 20rpx;
}

.action-btn {
  width: 120rpx;
  height: 60rpx;
  font-size: 24rpx;
  border-radius: 30rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.edit-btn {
  background-color: #07c160;
  color: #ffffff;
}

.delete-btn {
  background-color: #ff4444;
  color: #ffffff;
}

.republish-btn {
  background-color: #ff9800;
  color: #ffffff;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 30rpx;
}

.empty-image {
  width: 300rpx;
  height: 300rpx;
  margin-bottom: 40rpx;
  opacity: 0.6;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
  margin-bottom: 40rpx;
}

.publish-btn {
  width: 200rpx;
  height: 70rpx;
  background-color: #07c160;
  color: #ffffff;
  font-size: 28rpx;
  border-radius: 35rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
